package com.pzsh.sms.flybird;

import com.alibaba.fastjson.JSONObject;
import com.pzsh.enums.ErrorCodeEnum;
import com.pzsh.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FlyBird{
	public static void SendSms(String code,String mobile) {
		String account = "18821852888";
		String Pwd = "ef9eebafc805ec1e488317efe";
		String Content = "您的验证码为：" + code + "，该验证码5分钟内有效，请勿泄露于他人";
		String SignId = "213674";
		try {
			CloseableHttpClient client = null;
			CloseableHttpResponse response = null;
			try {
				List<BasicNameValuePair> formparams = new ArrayList<>();
				formparams.add(new BasicNameValuePair("Account",account));
				formparams.add(new BasicNameValuePair("Pwd",Pwd));
				formparams.add(new BasicNameValuePair("Content",Content));
				formparams.add(new BasicNameValuePair("Mobile",mobile));
				formparams.add(new BasicNameValuePair("SignId",SignId));

				HttpPost httpPost = new HttpPost("http://api.feige.ee/SmsService/Send");
				httpPost.setEntity(new UrlEncodedFormEntity(formparams,"UTF-8"));
				client = HttpClients.createDefault();
				response = client.execute(httpPost);
				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity);
				JSONObject jsonObject = JSONObject.parseObject(result);
				log.info(result);
				if (!jsonObject.getInteger("Code").equals(0)){
					throw new ApiException(ErrorCodeEnum.PARAM_200012);
				}
//				{"Message":"OK","RequestId":"F806C5A4-80A9-4C28-BF6C-1D2F95F66304","BizId":"718111877269657439^0","Code":"OK"}
//                {"SendId":"2019122518573165791764136","InvalidCount":0,"SuccessCount":1,"BlackCount":0,"Code":0,"Message":"OK"}
			} finally {
				if (response != null) {
					response.close();
				}
				if (client != null) {
					client.close();
				}
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage());
			throw new ApiException(ErrorCodeEnum.PARAM_200012);
		}
	}
}
